﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal struct XFExtNoFRT: IPropertyProvider
    {
        private List<ExtProp> _extProps;

        internal List<ExtProp> ExtProps
        {
            get
            {
                if (_extProps == null)
                    _extProps = new List<ExtProp>();
                return _extProps;
            }
        }
        public void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckStruct(delegate(ref XFExtNoFRT t, BinaryReader r) { t.Read(r); },
                                   delegate(ref XFExtNoFRT t, BinaryWriter w) { t.Write(w); }, reader, ref this);
#endif
            var reserved1 = reader.ReadUInt16();
            Contract.Assert(reserved1 == 0);
            var reserved2 = reader.ReadUInt16();
            Contract.Assert(reserved2 == 0xFFFF);
            var reserved3 = reader.ReadUInt16();
            Contract.Assert(reserved3 == 0);
            var cexts = reader.ReadUInt16();
            ExtProps.Clear();
            for (int i = 0; i < cexts; i++)
            {
                ExtProp p = new ExtProp();
                p.Read(reader);
                ExtProps.Add(p);
            }
        }

        public void Write(BinaryWriter writer)
        {
            writer.Write((ushort)0);
            writer.Write((ushort)0xFFFF);
            writer.Write((ushort)0);
            ushort cext = (ushort) ExtProps.Count;
            writer.Write(cext);
            foreach (var v in this.ExtProps)
                v.Write(writer);
        }

        public void AddProperty(ExtProp create)
        {
            this.ExtProps.Add(create);
        }

        public T GetPropertyValue<T>(ExtPropType type) where T : ExtPropValueBase
        {
            foreach (var prop in ExtProps)
            {
                if (prop.extType == type)
                    return (T)prop.value;

            }
            return null;
        }
    }
}